/** @format */

import axios from 'axios'
import { ChangeCreditsinfo, addCartInfo, GoodsInfo, BenefitInfo, JdBeanInfo } from './interface'
const crypto = require('crypto')

interface IJDResult {
  success: boolean
  code?: string
  desc?: string
  data?: any
}

// appKey加密签名
const getSHA = (str: string) => {
  const obj = crypto.createHash('sha1') // 与java的SHA加密方式生成的密钥相同
  obj.update(str)
  str = obj.digest('hex') // hex是十六进制
  // console.log(str, 'getSHA');
  return str
}

// 发送请求
const postJDRequest = async (apiName: string, ctx: any, data: Record<string, any>): Promise<any> => {
  const { openId, shopId, appKey, appSecret, venderId } = ctx
  if (!openId || !shopId || !appKey || !appSecret || !venderId) {
    return { success: false, desc: '参数context不完整' }
  }
  const result = await axios.post(`https://duiba-isv.isvjcloud.com/taobao/${apiName}`, {
    uid: openId,
    shopId,
    venderId: venderId,
    appKey,
    ...(data || {}),
    timestamp: new Date().getTime(),
    sign: getSHA(appSecret)
  })
  console.log(result.data, apiName, '——————postJDRequest res——————')
  return result?.data || { success: false, desc: '请求结果为空' }
}

/**
 * 发放优惠券
 * @param context
 * @param couponId 优惠券Id
 * @param uuid 发放记录唯一Id
 * @returns
 */
export const benefitSend = async (context: any, benefitInfo: BenefitInfo) => {
  if (!context) {
    return { success: false, desc: '参数context不能为空' }
  }
  const { couponId, uuid } = benefitInfo
  if (!couponId) {
    return { success: false, desc: '参数couponId不能为空' }
  }
  if (!uuid) {
    return { success: false, desc: '参数uuid不能为空' }
  }
  const result = await postJDRequest('sendCouponId', context, {
    couponId,
    uuid
  })
  return result
}

/**
 * 发放/消耗店铺积分
 * @param context
 * @param options 选项（businessId?, opt_type: 0增加 1减少, quantity: 数量）
 * @returns
 */
export const changeCredits = async (context: any, options: ChangeCreditsinfo) => {
  if (!context) {
    return { success: false, desc: '参数context不能为空' }
  }

  const { businessId, quantity, opt_type = 0, remark = `参与活动` } = options
  if (!businessId) {
    return { success: false, desc: '参数businessId不能为空' }
  }
  if (!quantity) {
    return { success: false, desc: '参数quantity不能为空' }
  }
  console.log('changeCredits param', context.openId, businessId, quantity, opt_type)
  // sendPoints  consumePoints
  const result = await postJDRequest(opt_type == 0 ? 'sendPoints' : 'consumePoints', context, {
    businessId,
    points: quantity,
    desc: remark
  })
  return result
}

/**
 * 获取店铺积分
 * @param context
 * @returns
 */
export const queryCredits = async (context: any) => {
  if (!context) {
    return { success: false, desc: '参数context不能为空' }
  }
  const result = await postJDRequest('getCustomerPoints', context, {})
  return result
}

/**
 * 会员信息
 * @param context
 * @returns
 */
export const queryVipinfo = async (context: any) => {
  if (!context) {
    return { success: false, desc: '参数context不能为空' }
  }
  const result = await postJDRequest('memberInfo', context, {})
  return result
}

/**
 * 是否是会员
 * @param context
 * @returns
 */
export const isMember = async (context: any) => {
  if (!context) {
    return { success: false, desc: '参数context不能为空' }
  }
  const result = await postJDRequest('isMember', context, {})
  return result
}

/**
 * 是否关注店铺
 * @param context
 * @returns
 */
export const isFollowShop = async (context: any) => {
  if (!context) {
    return { success: false, desc: '参数context不能为空' }
  }
  const result = await postJDRequest('isFollowShop', context, {})
  return result
}

/**
 * 关注店铺
 * @param context
 * @returns
 */
export const followShop = async (context: any) => {
  if (!context) {
    return { success: false, desc: '参数context不能为空' }
  }
  const result = await postJDRequest('followShop', context, {})
  return result
}

/**
 * 加购
 * @param context
 * @param item {itemId 商品skuId, num 加购数量}
 * @returns
 */
export const addCartItemByPin = async (context: any, item: addCartInfo) => {
  if (!context) {
    return { success: false, desc: '参数context不能为空' }
  }
  const { itemId } = item
  if (!itemId) {
    return { success: false, desc: '参数itemId不能为空' }
  }
  const result = await postJDRequest('addCartItemByPin', context, {
    itemId,
    num: 1
  })
  return result
}

/**
 * 收藏商品
 * @param context
 * @param productId 商品Id
 * @returns
 */
export const followGood = async (context: any, item: GoodsInfo) => {
  if (!context) {
    return { success: false, desc: '参数context不能为空' }
  }
  const { productId } = item
  if (!productId) {
    return { success: false, desc: '参数productId不能为空' }
  }
  const result = await postJDRequest('followGood', context, {
    productId
  })
  return result
}

// 发送京豆
export const sendBean = async (context: any, args: JdBeanInfo) => {
  const { requestId, beanNum, planId, desc } = args
  const { data } = await postJDRequest('sendBean', context, {
    requestId,
    beanNum,
    planId,
    desc // 参加[desc]-获得
  })
  return data || false
}
